<template>
  <div class="ad-template-avatar">
    <x-form :ref="setItemRef" v-model:model="getProps.params" :rules="rules">
      <n-form-item :label="getProps.params.description" path="default">
        <n-select
          v-model:value="getProps.params.default"
          class="select-n"
          :placeholder="getProps.params.description"
          :options="list"
          style="width: 100%"
          :render-label="renderLabel"
          :render-option="renderOption"
          :render-tag="renderTag"
          label-field="profileName"
          value-field="profileId"
          :loading="loading"
        >
          <template #action>
            <span>找不到？请新建</span>
            <em style="color: #536fff; cursor: pointer" @click="showAdd">头像及昵称跳转页</em>
            <n-divider vertical />
            <em style="color: #536fff; cursor: pointer" @click="getAvatarList">刷新</em>
          </template>
        </n-select>
      </n-form-item>
    </x-form>
    <n-modal
      v-if="dialogVisible"
      v-model:show="dialogVisible"
      preset="card"
      title="上传头像及昵称"
      :style="{ width: '500px' }"
      class="x-dialog-addAvatar"
    >
      <x-form ref="addAvatar" v-model:model="updateData" :rules="updateRules" label-placement="left" label-width="80px">
        <n-form-item label="头像" path="headImageId">
          <FUpload :key="updateData.uuid" :loading="upload" :params="uploadParams" @finish="onSuccess" @error="onError">
            <dl v-if="!updateData.headImageId" class="f-upload-tips">
              <dt>512*512</dt>
              <dd>
                <p>点击上传图片</p>
                <p>JPG/PNG，400KB</p>
              </dd>
            </dl>
            <n-image v-else :src="picUrl" fit="contain" :preview-disabled="true" />
          </FUpload>
        </n-form-item>
        <n-form-item label="名称" path="profileName">
          <n-input v-model:value="updateData.profileName" maxlength="12" placeholder="请输入名称">
            <template #suffix class="n-input__count">
              <span class="n-input__count-inner">
                {{ updateData.profileName?.length > 0 ? updateData.profileName.length : 0 }}/12
              </span>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item label="详细描述" path="description">
          <n-input v-model:value="updateData.description" maxlength="120" placeholder="请输入详情描述">
            <template #suffix class="n-input__count">
              <span class="n-input__count-inner">
                {{ updateData.description?.length > 0 ? updateData.description.length : 0 }}/120
              </span>
            </template>
          </n-input>
        </n-form-item>
      </x-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="dialogVisible = false">取消</n-button>
          <n-button type="primary" @click="onSaveAvatar">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
  import { useRoute, useRouter } from 'vue-router'
  import { computed, h, reactive, ref, nextTick, onMounted, onBeforeUpdate, onUpdated, VNode } from 'vue'
  import { v4 as uuidv4 } from 'uuid'
  import { formatLength } from '@/utils/index'

  import {
    NModal,
    NInput,
    NImage,
    NDivider,
    NButton,
    useMessage,
    NSpace,
    NTooltip,
    NSelect,
    NFormItem,
    SelectRenderLabel,
    NText,
    SelectOption,
    NAvatar
  } from 'naive-ui'
  import { useStore } from '@/store'
  import FUpload from '@/views/advertising/ads/create/components/step7/FUpload.vue'
  import { XIcon, XForm } from '@/components'

  const message = useMessage()
  const router = useRouter()
  const route = useRoute()
  const store = useStore()
  const emit = defineEmits(['change', 'upload'])
  const props = defineProps({
    params: {
      type: Object,
      default: () => ({})
    }
  })
  const getProps = reactive(props)
  const accountCode = computed(() => {
    return store.state.intelligent.data.accountCode
  })
  const templateId = computed(() => {
    return store.state.intelligent.data.creative.templateId
  })
  const promotionTarget = computed(() => {
    return store.state.intelligent.data.base.promotionTarget
  })
  const siteSet = computed(() => {
    return store.state.intelligent.data.position.promotionTarget
  })
  const uploadParams = computed(() => {
    return {
      accept: '.jpg,.png',
      data: {
        accountCode: accountCode.value,
        imageWidth: 512,
        imageHeight: 512,
        fileSize: 400
      },
      rules: {
        width: 512,
        height: 512,
        fileSize: 400
      }
    }
  })

  const inputRef = ref()
  const loading = ref(true)
  const upload = ref(false)
  const dialogVisible = ref(false)
  const rules = ref({
    default: []
  })
  const list = ref([])
  const picUrl = ref()
  const updateData = ref({
    uuid: uuidv4(),
    headImageId: null,
    profileName: null,
    description: null
  })
  const updateRules = ref({
    profileName: { type: 'string', required: true, message: '请输入名称', trigger: ['blur', 'change'] },
    description: { type: 'string', required: true, message: '请输入详情描述', trigger: ['blur', 'change'] },
    headImageId: { type: 'any', required: true, message: '请上传头像' }
  })
  const addAvatar = ref()
  const renderTag: SelectRenderLabel = ({ option }) => {
    return option.profileName
  }
  const renderOption = ({ node, option }: { node: VNode; option: SelectOption }) =>
    h(
      'div',
      {
        style: {
          width: '100%'
        }
      },
      node
    )
  // 自定义下拉
  const renderLabel: SelectRenderLabel = (option) => {
    return h(
      'div',
      {
        style: {
          display: 'flex',
          alignItems: 'center'
        }
      },
      [
        h(
          NText,
          {
            style: {
              flex: 1
            }
          },
          () => option.profileName
        ),
        h(
          'div',
          {
            style: {
              flex: 1,
              marginLeft: '12px',
              padding: '4px 0',
              position: 'absolute',
              right: '30px',
              bottom: 0
            }
          },
          [
            h(
              NTooltip,
              {
                onUpdateShow: (val: boolean) => onDelete(option),
                trigger: 'click'
              },
              {
                trigger: () => h(XIcon, { class: 'iconfont icon-036' }),
                default: () => '删除'
              }
            )
          ]
        )
      ]
    )
  }

  const itemRefs = {}
  const setItemRef = (el: any) => {
    if (el) {
      const key = getProps.params.name
      itemRefs[key] = el
    }
  }
  onMounted(() => {
    initRules()
    getAvatarList()
  })

  // 初始化校验规则
  function initRules() {
    // 必填、可选
    if (getProps.params.required) {
      rules.value.default.push({
        type: 'any',
        required: getProps.params.required,
        message: `请选择${getProps.params.description}`,
        trigger: ['blur', 'change']
      })
    }
  }
  // 展示新建弹出
  function showAdd() {
    dialogVisible.value = true
    picUrl.value = null
    updateData.value = {
      uuid: uuidv4(),
      headImageId: null,
      profileName: null,
      description: null
    }
    nextTick(() => {
      itemRefs[getProps.params.name].restoreValidation()
      // this.$refs[getProps.params.name].clearValidate()
    })
  }
  // 校验
  function validate() {
    return new Promise((resolve, reject) => {
      itemRefs[getProps.params.name].validate((errors) => {
        if (!errors) {
          resolve({
            [getProps.params.name]: getProps.params.default
          })
        } else {
          message.warning(`请选择${getProps.params.description}`)
          resolve(false)
        }
      })
    })
  }
  // 头像列表
  function getAvatarList() {
    loading.value = true
    store
      .dispatch('intelligent/getAdsProfiles', {
        accountCode: accountCode.value
      })
      .then((res) => {
        list.value = res.data
        loading.value = false
      })
  }
  function onProgress() {
    upload.value = true
  }
  function onError() {
    upload.value = false
  }
  // 上传成功
  function onSuccess(res) {
    upload.value = false
    updateData.value.uuid = uuidv4()
    updateData.value.headImageId = String(res.mediaId)
    picUrl.value = res.previewUrl
    nextTick(() => {
      addAvatar.value.restoreValidation()
    })
  }
  // 新增头像
  function onSaveAvatar() {
    addAvatar.value.validate((errors) => {
      if (!errors) {
        const params = {
          ...updateData.value,
          accountCode: accountCode.value,
          promotionTarget: promotionTarget.value
        }
        store.dispatch('intelligent/getAdsProfilesAdd', params).then((res) => {
          dialogVisible.value = false
          getProps.params.default = res.data.profile_id
          // this.$set(getProps.params, 'default', res.profile_id)
          getAvatarList()
        })
      } else {
        console.log('上传失败')
      }
    })
  }
  // 删除某条数据
  function onDelete(row: any) {
    store
      .dispatch('intelligent/getAdsCanvasPageDel', {
        accountCode: accountCode.value,
        profileId: row.profileId
      })
      .then(() => {
        getAvatarList()
        getProps.params.default = null
        // this.$set(getProps.params, 'default', null)
      })
  }
  defineExpose({
    validate
  })
</script>
<style lang="scss">
  .select-n {
    :deep(.n-base-select-menu .n-base-select-option .n-base-select-option__content) {
      flex: 1;
    }
  }
</style>
<style scoped lang="scss">
  .select-n {
    :deep(.n-base-select-option__content) {
      flex: 1;
    }
  }
  .ad-template-brand-option {
    color: #999;
    cursor: default !important;
    em {
      font-style: normal;
      color: #fa5a53;
      cursor: pointer;
    }
  }
  .x-dialog-addAvatar {
    dl,
    dt,
    dd,
    p {
      margin: 0;
      padding: 0;
    }
    .f-upload-tips {
      text-align: center;
      color: #888;
      flex: 1;
      dd {
        font-size: 12px;
      }
      &:hover {
        color: #666;
        cursor: pointer;
      }
    }
    .f-ad-upload {
      width: 160px;
      height: 160px;
      background-color: #fafafa;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
    }
    .el-upload {
      height: 100%;
      display: flex;
      align-items: center;
    }
    .el-progress__text {
      font-size: 13px !important;
      display: block;
      padding-top: 3px;
    }
  }
</style>
